<?php

namespace app\manage\services;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelSystem;
use app\common\loader\Services;
use yiqiniu\extend\facade\Arrays;
use yiqiniu\extend\facade\Db;


/**
 *  菜单管理
 */
class MerchantMenuService extends BaseService
{


    protected $action = [
        'login',
        'group_menu',
        'group_permission'
    ];

    /**
     *  获取菜单列表
     * @param array $option
     * @param bool $tree
     * @return array
     * @throws \think\Exception
     */
    public function menuList(array $option, bool $tree = false): array
    {
        if (empty($option['field'])) {
            $option['field'] = 'id,title,pid,child,order_id,is_show';
        }
        $list = ModelMerchant::MerchantSystemMenu()->select($option);
        if ($tree) {
            $list = Arrays::toTree($list, 'id', 'pid');
        }
        return $list;
    }

    /**
     * 菜单详情
     * @param $option
     * @return array
     * @throws \think\Exception
     */
    public function menuInfo($option): array
    {
        if (empty($option['field'])) {
            $option['field'] = 'id,title,pid,child,order_id,front,page_action,icon';
        }
        $info = ModelMerchant::MerchantSystemMenu()->find($option);
        if (empty($info)) {
            api_exception(400, '菜单不存在或已删除，请刷新后重试！');
        }
        return $info;

    }

    /**
     * 删除菜单
     * @param $id
     * @throws \think\Exception
     */
    public function menuDel($id): void
    {
        ModelMerchant::MerchantSystemMenu()->del($id);
    }

    /**
     * 保存菜单
     * @param $data
     * @throws \think\Exception
     */

    public function menuSave($data): void
    {
        $data["order_id"] = !empty($data["order_id"]) ? $data["order_id"] : 200;
        // 组合前端参数
        if (!empty($data['front'])) {
            $front = $data['front'];
            $front['auth'] = $data['page_action'];
            $front['title'] = $data['title'];
            $data['front'] = json_encode($front, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
        }
        if (!empty($data['pid']) && $data['pid'] < 0) {
            $data['pid'] = 0;
        }
        ModelMerchant::MerchantSystemMenu()->addEdit($data);
    }

    /**
     * 保存菜单filed
     * @param $data
     * @throws \think\Exception
     */
    public function interfaceFiledSave($data): void
    {
        $data["sort"] = !empty($data["sort"]) ? $data["sort"] : 200;
        $id = $data['id'] ?? 0;
        unset($data['id']);
        $data['update_at'] = Dt()->format();
      $model =   ModelMerchant::MerchantSystemApi();
        if ($id > 0) {
            $model->removeOption()->update(['id' => $id], $data);
        } else {
            $data['type_id'] = 2;
            $model->removeOption()->insert($data);
        }
    }

    /**
     *  获取接口列表
     * @param array $option
     * @param int $type
     * @return array
     * @throws \think\Exception
     */
    public function interfaceList(array $option, int $type = 0): array
    {
        $list = ModelMerchant::MerchantSystemApi()->select($option);
        Services::Helper()->showListTitle($list, ['merchant_system_api' => 'pid'], ['auth' => 'system.interface_auth', 'type_id' => 'system.interface_type']);
        if ($type === 2) {
            $child_count = ModelMerchant::MerchantSystemApi()->where(['type_id' => ['=', 1], 'pid' => ['=', 0]])->count();
            $system_menu = config('system.system_menu');
            $list = array_merge($system_menu, $list);
            foreach ($list as &$v) {
                $v['child'] = !empty($v['child']) ? $v['child'] : 0;
                if (empty($v['id'])) {
                    $v['child'] = $child_count;
                }
            }
        }
        foreach ($list as &$v) {
            if (is_numeric($v['id']) && !empty($v['id'])) {
                $v['group_name'] = $v['pid_tag'];
            }
        }
        return $list;
    }

    /**
     * 接口详情
     * @param $option
     * @return array
     * @throws \think\Exception
     */
    public function interfaceInfo($option): array
    {
        $info = ModelMerchant::MerchantSystemApi()->find($option);
        if (empty($info)) {
            api_exception(400, '接口不存在或已删除，请刷新后重试！');
        }
        return $info;
    }

    /**
     * 删除菜单
     * @param $id
     * @throws \think\Exception
     */
    public function interfaceDel($id): void
    {
        ModelMerchant::MerchantSystemApi()->where(["id" => $id])->delete();
    }

    /**
     * 保存菜单
     * @param $data
     * @throws \think\Exception
     */

    public function interfaceSave($data): void
    {
        $data["sort"] = !empty($data["sort"]) ? $data["sort"] : 200;
        $id = $data['id'] ?? 0;
        unset($data['id']);
        $data['update_at'] = Dt()->format();
        $model = ModelMerchant::MerchantSystemApi();
        if ($id > 0) {
            //获取修改前的数据
            $oldData = $model->where(["id" => $id])->find();
            if (empty($oldData)) {
                api_exception(API_ERROR, "该信息不存在或已被管理员删除！请返回刷新后重新操作！");
            }
            //如果原始数据parent_id不等于新数据的parent_id
            if (!empty($data['pid']) && $oldData['pid'] !== $data['pid']) {
                $model->removeOption()->where(["id" => $data['pid']])->update([], ['child' => Db::raw('child+1')]);
                if (!empty($oldData['pid'])) {
                    $model->removeOption()->where(["id" => $oldData['pid']])->update([], ['child' => Db::raw('child-1')]);
                }
            }
            $model->removeOption()->update(['id' => $id], $data);
        } else {
            $data['type_id'] = 2;
            $model->removeOption()->insert($data);
        }
    }

    /**
     * 重新载入接口
     * @param string $module
     * @return int
     * @throws \yiqiniu\extend\exception\ApiException
     */
    public function interfaceOverload(string $module)
    {

        $jsonRules = $this->getRouteList($module);

        return ModelMerchant::MerchantSystemApi()->jsonSaveToTable($jsonRules, $module);
    }

    /**
     *  获取菜单列表
     * @param array $option
     * @param bool $tree
     * @return array
     * @throws \think\Exception
     */
    public function menuLists(array $option, bool $tree = false): array
    {
        if (empty($option['field'])) {
            $option['field'] = 'id,title,pid,child,order_id,is_show';
        }

        $list = ModelSystem::SystemMenu()->select($option);
        if ($tree) {
            $list = Arrays::toTree($list, 'id', 'pid');
        }
        return $list;
    }
}
